package controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class CouponServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String coupon = request.getParameter("coupon");
		
		if(coupon!=null)
		{
			DBCollection collection = Data.data("coupon");
			DBObject dbObject2 = collection.findOne(new BasicDBObject("coupon",coupon));
			if(dbObject2!=null)
			{
				DBCollection coll = Data.data("users");
				
				int coin = 0;
				if(dbObject.get("coin")!=null)
				{
					coin = Integer.parseInt(dbObject.get("coin").toString());
				}
				coin += Integer.parseInt(dbObject2.get("day").toString());
				
				dbObject.put("coin", coin);
				coll.findAndModify(new BasicDBObject("username",dbObject.get("username")), dbObject);
				
				collection.remove(dbObject2);
				
				request.setAttribute("info", "Your get "+dbObject2.get("day")+" credit");
			} else {
				request.setAttribute("info", "Coupon is not valid");
			}
		} else {
			request.setAttribute("info", "Input the coupon code or blog");
		}
		
		try {
			request.getRequestDispatcher("/coupon.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
